home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
EnigmA Amiga Run 1999 January
/
EnigmA AMIGA RUN 33 (1999)(G.R. Edizioni)(IT)[!][issue 1999-01].iso
/
earcd
/
faq
/
c-faq
/
diff.z
/
diff
Wrap
Text File
|
1999-01-01
|
44KB
|
992 lines
Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers
Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!hookup!usenet.eel.ufl.edu!news.mathworks.com!hunter.premier.net!www.nntp.primenet.com!nntp.primenet.com!news.sprintlink.net!news-stk-200.sprintlink.net!eskimo!scs
From: scs@eskimo.com (Steve Summit)
Subject: comp.lang.c Changes to Answers to Frequently Asked Questions (FAQ)
X-Nntp-Posting-Host: eskimo.com
Message-ID: <1996Sep06.0727.scs.0002@eskimo.com>
Followup-To: poster
Originator: scs@eskimo.com
Sender: news@eskimo.com (News User Id)
Reply-To: scs@eskimo.com
X-Pgp-Signature: Version: 2.6.2
iQCSAwUBMjA+Pd6sm4I1rmP1AQH5LAPomQthZFXyG6sOboEJPHy5xDLWdiU6vh86
8j5oH1icPLXn6wvRJ1wvU3rzOuRbE83GEt909c+0qt1qiJbwVeqMHzM4WPy89YNL
2nsdMvRG9QB46SWfXyoKU64KOIvVsw3HtUGm0OPErBqiHvYAAyzKHdJRCyqmAIbO
ElHduaY=
=A7ou
X-Archive-Name: C-faq/diff
Organization: only when absolutely necessary
Date: Fri, 6 Sep 1996 14:28:10 GMT
Approved: news-answers-request@MIT.Edu
Lines: 968
Xref: senator-bedfellow.mit.edu comp.lang.c:203431 comp.lang.c.moderated:5291 comp.answers:20966 news.answers:81117
Archive-name: C-faq/diff
Comp-lang-c-archive-name: C-FAQ-list.diff
This article contains the significant differences between the
previous version of the comp.lang.c FAQ list (version 3.3, last
modified April 3, 1996, last posted August 1, 1996) and the
current one (version 3.4). These diffs have been heavily
edited, for readability's sake, and are not suitable as input to
a patch program.
In spite of having spent way too much time on this update (and
not even having that many visible changes to show for it), I have
unfortunately not managed to acknowledge all of the suggestions
in the current pile. Eternal apologies to those of you who have
still not heard from me or seen your suggestion used here, even
after many months.
First, here are a few brand-new entries:
==========
> 1.31a: What's wrong with this initialization?
>
> char *p = malloc(10);
>
> My compiler is complaining about an "invalid initializer," or
> something.
>
> A: Is it in the declaration of a static or non-local variable?
> Function calls are not allowed in initializers for such
> variables.
==========
> 11.2a: Where can I get information about updates to the Standard?
>
> A: You can find some information at the web sites
> http://www.lysator.liu.se/c/index.html and http://www.dmk.com/ .
==========
> 16.2a: I'm getting baffling syntax errors which make no sense at all,
> and it seems like large chunks of my program aren't being
> compiled.
>
> A: Check for unclosed comments or mismatched #if/#ifdef/#ifndef/
> #else/#endif directives; remember to check header files, too.
> (See also questions 2.18, 10.9, and 11.29.)
==========
> 16.2b: Why isn't my procedure call working? The compiler seems to skip
> right over it.
>
> A: Does the code look like this?
>
> myprocedure;
>
> C only has functions, and function calls always require
> parenthesized argument lists, even if empty. Use
>
> myprocedure();
==========
> 18.15c: Where are some collections of useful code fragments and
> examples?
>
> A: Bob Stout's "SNIPPETS" collection is available from
> ftp.brokersys.com in directory pub/snippets or on the web at
> http://www.brokersys.com/snippets/ .
>
> Lars Wirzenius's "publib" library is available from ftp.funet.fi
> in directory pub/languages/C/Publib/.
>
> See also questions 14.12, 18.9, 18.13, and 18.16.
==========
> 19.12a: How can I find the modification date and time of a file?
>
> A: The Unix and POSIX function is stat(), which several other
> systems supply as well. (See also question 19.12.)
==========
And here are the changes to existing text:
==========
< [Last modified April 3, 1996 by scs.]
---
> [Last modified September 5, 1996 by scs.]
==========
refute. Several noteworthy books on C are listed in this article's
< bibliography; see also question 18.10. Many of the questions and
< answers are cross-referenced to these books, for further study by the
< interested and dedicated reader (but beware of ANSI vs. ISO C Standard
< section numbers; see question 11.1).
---
> bibliography; see also questions 18.9 and 18.10. Many of the questions
> and answers are cross-referenced to these books, for further study by
> the interested and dedicated reader.
==========
< This article was last modified on April 3, 1996, and its travels
may have taken it far from its original home on Usenet. It may now
be out-of-date, particularly if you are looking at a printed copy or one
< retrieved from a tertiary archive site or CD-ROM. You can always obtain
---
> This article was last modified on September 5, 1996, and its travels
may have taken it far from its original home on Usenet. It may now
be out-of-date, particularly if you are looking at a printed copy or one
> retrieved from a tertiary archive site or CD-ROM. You should be able to
> obtain the most up-to-date copy by anonymous ftp from sites ftp.eskimo.com,
rtfm.mit.edu, or ftp.uu.net (see questions 18.16 and 20.40), or by
sending the e-mail message "help" to mail-server@rtfm.mit.edu .
==========
< (The question numbers within each section are not continuous because
< they are aligned with the forthcoming book-length version, which
< contains even more questions.)
---
> (The question numbers within each section are not always continuous,
> because they are aligned with the aforementioned book-length version,
> which contains even more questions.)
==========
< A: Variables with "static" duration (that is, those declared
< outside of functions, and those declared with the storage class
< static), are guaranteed initialized (just once, at program
< startup) to zero, as if the programmer had typed "= 0".
< Therefore, such variables are initialized to the null pointer
---
> A: Uninitialized variables with "static" duration (that is, those
> declared outside of functions, and those declared with the
> storage class static), are guaranteed to start out as zero, as
> if the programmer had typed "= 0". Therefore, such variables
> are implicitly initialized to the null pointer (of the correct
type; see also section 5) if they are pointers, and to 0.0 if
they are floating-point.
==========
A: The first form declares a "structure tag"; the second declares a
< "typedef". The main difference is that the second declaration
---
> "typedef". The main difference is that you subsequently refer
> to the first type as "struct x1" and the second as "x2". That
is, the second declaration is of a slightly more abstract type --
its users don't necessarily know that it is a structure, and
the keyword struct is not used when declaring instances of it.
==========
However, it looks like this technique is disallowed by a strict
< interpretation of the Standard as well.
---
> interpretation of the Standard as well. Furthermore, either of
> these "chummy" structures must be used with care, since the
> programmer knows more about their size than the compiler does.
> (In particular, they can generally only be manipulated via
> pointers.)
==========
< A: ANSI Standard C allows an initializer for the first member of a
< union. There is no standard way of initializing any other
---
> A: ANSI Standard C allows an initializer for the first-named member
> of a union. There is no standard way of initializing any other
==========
3.3: I've experimented with the code
< [CENSORED]
---
> int i = 3;
> i = i++;
on several compilers. Some gave i the value 3, some gave 4, but
one gave 7. I know the behavior is undefined, but how could it
==========
< A: [I apologize for the censorship of the question, but the
< expression that used to be there was indecent, and by the
< newly-passed Communications Decency Act of the U.S., I am
< prohibited from transmitting "indecent" material, whatever that
< is. Suffice it to say that the expression tried to modify the
< same variable twice between sequence points. --scs]
==========
3.9 and 11.33. (Also, note that neither i++ nor ++i is the same
< as i+1. If you want to increment i, use i=i+1 or i++ or ++i,
< not some combination. See also question 3.12.)
---
> as i+1. If you want to increment i, use i=i+1, i+=1, i++, or
> ++i, not some combination. See also question 3.12.)
==========
A: There is a special exception for those operators (as well as the
< ?: operator): left-to-right evaluation is guaranteed (as is an
---
> ?: and comma operators): left-to-right evaluation is guaranteed
(as is an intermediate sequence point, see question 3.8).
==========
A: Since the two forms differ only in the value yielded, they are
entirely equivalent when only their side effect is needed.
> (However, the prefix form is preferred in C++.)
==========
A: This message, which typically occurs with MS-DOS compilers (see,
therefore, section 19) means that you've written, via a null
< (perhaps because uninitialized) pointer, to location 0.
---
> (perhaps because uninitialized) pointer, to an invalid location
> (probably offset 0 in the default data segment).
==========
three places past (the start of) the object *named* a, while
p[3] is three places past the object *pointed to* by p. In the
example above, both a[3] and p[3] happen to be the character
< 'l', but the compiler gets there differently.
---
> 'l', but the compiler gets there differently. (The essential
> difference is that the values of an array like a and a pointer
> like p are computed differently *whenever* they appear in
> expressions, whether or not they are being subscripted, as
> explained further in the next question.)
==========
< 6.14: How can I set an array's size at compile time?
---
> 6.14: How can I set an array's size at run time?
How can I avoid fixed-sized arrays?
==========
#include <stdlib.h>
< int *dynarray = (int *)malloc(10 * sizeof(int));
---
#include <stdlib.h>
> int *dynarray;
> dynarray = malloc(10 * sizeof(int));
==========
< You can keep the array's contents contiguous, while making later
< reallocation of individual rows difficult, with a bit of
---
> You can keep the array's contents contiguous, at the cost of
> making later reallocation of individual rows more difficult,
with a bit of explicit pointer arithmetic:
==========
In either case, the elements of the dynamic array can be
accessed with normal-looking array subscripts: arrayx[i][j] (for
< 0 <= i <= NROWS and 0 <= j <= NCOLUMNS).
---
> 0 <= i < NROWS and 0 <= j < NCOLUMNS).
==========
A: Before ANSI/ISO Standard C introduced the void * generic pointer
type, these casts were typically required to silence warnings
(and perhaps induce conversions) when assigning between
< incompatible pointer types. (Under ANSI/ISO Standard C, these
< casts are no longer necessary.)
---
> incompatible pointer types.
>
> Under ANSI/ISO Standard C, these casts are no longer necessary,
> and in fact modern practice discourages them, since they can
> camouflage important warnings which would otherwise be generated
> if malloc() happened not to be declared correctly; see question
> 7.6 above.
==========
A: It's never necessary to multiply by sizeof(char), since
sizeof(char) is, by definition, exactly 1. (On the other hand,
< multiplying by sizeof(char) doesn't hurt, and may help by
---
> multiplying by sizeof(char) doesn't hurt, and in some
> circumstances may help by introducing a size_t into the
expression.) See also question 8.9.
==========
A: When you call free(), the memory pointed to by the passed
pointer is freed, but the value of the pointer in the caller
< remains unchanged, because C's pass-by-value semantics mean that
---
> probably remains unchanged, because C's pass-by-value semantics
mean that called functions never permanently change the values
of their arguments. (See also question 4.8.)
==========
7.23: I'm allocating structures which contain pointers to other
dynamically-allocated objects. When I free a structure, do I
< have to free each subsidiary pointer first?
---
> also have to free each subsidiary pointer?
==========
10.15: Is there anything like an #ifdef for typedefs?
< A: Unfortunately, no. (See also question 10.13.)
---
> A: Unfortunately, no. You may have to keep sets of preprocessor
> macros (e.g. MY_TYPE_DEFINED) recording whether certain typedefs
> have been declared. (See also question 10.13.)
==========
< 10.23: How can I use a macro argument inside a string literal in the
< macro expansion?
<
< A: See question 11.18.
---
> 10.23-4: I'm having trouble using macro arguments inside string
> literals, using the `#' operator.
>
> A: See questions 11.17 and 11.18.
==========
It is often better to use a bona-fide function, which can take a
variable number of arguments in a well-defined way. See
< questions 15.4 and 15.5.
---
> questions 15.4 and 15.5. (If you needed a macro replacement,
> try using a function plus a non-function-like macro, e.g.
> #define printf myprintf .)
==========
internationalization. The production of Technical Corrigenda is
an ongoing process, and a second one is expected in late 1995.
In addition, both ANSI and ISO require periodic review of their
< standards. This process is beginning in 1995, and will likely
---
> standards. This process began in 1995, and will likely result
in a completely revised standard (nicknamed "C9X" on the
assumption of completion by 1999).
==========
assigned to. The value of a const-qualified object is therefore
*not* a constant expression in the full sense of the term. (C
is unlike C++ in this regard.) When you need a true compile-
< time constant, use a preprocessor #define.
---
> time constant, use a preprocessor #define (or perhaps an enum).
==========
A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or
#ifndef must still consist of "valid preprocessing tokens."
< This means that there must be no newlines inside quotes, and no
< unterminated comments or quotes (note particularly that an
---
> This means that the characters " and ' must each be paired just
> as in real C code, and the pairs mustn't cross line boundaries.
> (Note particularly that an apostrophe within a contracted word
looks like the beginning of a character constant.) Therefore,
natural-language comments and pseudocode should always be
written between the "official" comment delimiters /* and */.
==========
A: The #pragma directive provides a single, well-defined "escape
< hatch" which can be used for all sorts of implementation-
---
> hatch" which can be used for all sorts of (nonportable)
implementation-specific controls and extensions: source listing
control, structure packing, warning suppression (like lint's old
/* NOTREACHED */ comments), etc.
==========
11.21: What does "#pragma once" mean? I found it in some header files.
A: It is an extension implemented by some preprocessors to help
< make header files idempotent; it is essentially equivalent to
< the #ifndef trick mentioned in question 10.7.
---
> make header files idempotent; it is equivalent to the #ifndef
> trick mentioned in question 10.7, though less portable.
==========
Finally, are you sure you really need to convert lots of old
code to ANSI C? The old-style function syntax is still
< acceptable, and a hasty conversion can easily introduce bugs.
---
> acceptable (except for variadic functions; see section 15), and
a hasty conversion can easily introduce bugs.
==========
(which apply in variable-length argument lists such as
printf's, whether or not prototypes are in scope), values of
type float are promoted to double, and printf() therefore sees
< only doubles. See also questions 12.13 and 15.2.
---
> only doubles. (printf() does accept %Lf, for long double.) See
> also questions 12.13 and 15.2.
==========
often useful; see also question 13.6.) If you do use sscanf(),
< don't forget to check the return value to make sure that the
< expected number of items were found.
---
> be sure to check the return value to make sure that the expected
> number of items were found. Also, if you use %s, be sure to
> guard against buffer overflow.
==========
< strlen() on the string(s) to be inserted. You can
< conservatively estimate the size that %d will expand to with
< code like:
<
< #include <limits.h>
< char buf[(sizeof(int) * CHAR_BIT + 2) / 3 + 1 + 1];
< sprintf(buf, "%d", n);
<
< (This code computes the number of characters required for a base-
---
> strlen() on the string(s) to be inserted. The number of
> characters produced by %d is no more than
>
> ((sizeof(int) * CHAR_BIT + 2) / 3 + 1) /* +1 for '-' */
>
> (CHAR_BIT is in <limits.h>), though this computation may be over-
> conservative. (It computes the number of characters required for
a base-8 representation of a number; a base-10 expansion is
guaranteed to take as much room or less.)
==========
(and inadvisable). A last-ditch technique which is sometimes
suggested is to use fprintf() to print the same text to a bit
bucket or temporary file, and then to look at fprintf's return
< value or the size of the file (but see question 19.12).
---
> value or the size of the file (but see question 19.12, and worry
> about write errors).
==========
If there's any chance that the buffer might not be big enough,
you won't want to call sprintf() without some guarantee that the
buffer will not overflow and overwrite some other part of
< memory. Several stdio's (including GNU and 4.4bsd) provide the
---
> memory. If the format string is known, you can limit %s
> expansion by using %.Ns for some N, or %.*s (see also question
> 12.10). Several stdio's (including GNU and 4.4bsd) provide the
obvious snprintf() function, which can be used like this:
==========
output operation goes on to complete successfully, errno still
contains ENOTTY. (Note that it is only meaningful for a program
to inspect the contents of errno after an error has been
< reported.)
---
> reported; errno is not guaranteed to be 0 otherwise.)
==========
< A: fgetpos() and fsetpos() use a special typedef, fpos_t, for
< representing offsets (positions) in a file. The type behind
< this typedef, if chosen appropriately, can represent arbitrarily
< large offsets, allowing fgetpos() and fsetpos() to be used with
< arbitrarily huge files. ftell() and fseek(), on the other hand,
< use long int, and are therefore limited to offsets which can be
< represented in a long int. See also question 1.4.
---
> A: ftell() and fseek() use type long int to represent offsets
> (positions) in a file, and are therefore limited to offsets of
> about 2 billion (2**31-1). The newer fgetpos() and fsetpos()
> functions, on the other hand, use a special typedef, fpos_t, to
> represent the offsets. The type behind this typedef, if chosen
> appropriately, can represent arbitrarily large offsets, so
> fgetpos() and fsetpos() can be used with arbitrarily huge files.
> See also question 1.4.
==========
There is no standard way to discard unread characters from a
< stdio input stream, nor would such a way be sufficient unread
< characters can also accumulate in other, OS-level input buffers.
---
> stdio input stream, nor would such a way be sufficient, since
> unread characters can also accumulate in other, OS-level input
> buffers. You may be able to read and discard characters until
> \n, or use the curses flushinp() function, or use some system-
> specific technique. See also questions 19.1 and 19.2.
==========
an fseek or fflush is always required between reading and
writing in the read/write "+" modes. Also, remember that you
can only overwrite characters with the same number of
< replacement characters; see also question 19.14.
---
> replacement characters, and that overwriting in text mode may
> truncate the file at that point. See also question 19.14.
==========
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
< /* now compare sp1->whatever and sp2-> ... */
---
> /* now compare sp1->whatever and sp2-> ... */
==========
cause overflow. Note also that at daylight saving time
< changeovers, local days are not 24 hours long.
---
> changeovers, local days are not 24 hours long (so don't assume
> that division by 86400 will be exact).
==========
< A: In some cases (especially if the functions are nonstandard) you
< may have to explicitly ask for the correct libraries to be
< searched when you link the program.
---
> A: In general, a header file contains only declarations. In some
> cases (especially if the functions are nonstandard) you may have
> to explicitly ask for the correct libraries to be searched when
> you link the program (#including the header doesn't do that).
==========
< A: That message is a quirk of the old Unix linkers. You only get
< an error about _end being undefined when other things are
---
> A: That message is a quirk of the old Unix linkers. You get an
> error about _end being undefined only when other things are
undefined, too -- fix the others, and the error about _end will
disappear.
==========
< if(fabs(a - b) <= epsilon * a)
---
> if(fabs(a - b) <= epsilon * fabs(a))
==========
< for some suitably-chosen epsilon.
---
> for some suitably-chosen degree of closeness epsilon (as long as
> a is nonzero!).
==========
< This technique won't work properly for negative numbers, though.
---
> This technique won't work properly for negative numbers,
> though (for which you could use something like
> (int)(x < 0 ? x - 0.5 : x + 0.5)).
==========
A: That constant (which is apparently supposed to be the value of
pi, accurate to the machine's precision), is not standard. If
< you need pi, you'll have to #define it yourself.
---
> you need pi, you'll have to #define it yourself, or compute it
> with 4*atan(1.0).
==========
A: Ajay Shah maintains an index of free numerical software; it is
< posted periodically, and available where this FAQ list is
< archived (see question 20.40).
---
> posted periodically, and archived in the comp.lang.c directory
> at rtfm.mit.edu (see question 20.40).
==========
14.13: I'm having trouble with a Turbo C program which crashes and says
something like "floating point formats not linked."
< A: The message in the question has to do with an indecent problem
< in Borland's compilers, which for some unfathomable reason has
< still not been fixed. However, by the newly-passed
< Communications Decency Act of the U.S., I am prohibited from
< transmitting or discussing "indecent" material. (If the fact
< that users of Borland's compilers are still having this problem
< isn't indecent, I don't know what is.) If you send me e-mail
< certifying that you are over 18 years of age, I may be able to
< help you. (You may also be able to see the
---
> A: Some compilers for small machines, including Borland's (and
> Ritchie's original PDP-11 compiler), leave out certain floating
> point support if it looks like it will not be needed. In
> particular, the non-floating-point versions of printf() and
> scanf() save space by not including code to handle %e, %f, and
> %g. It happens that Borland's heuristics for determining
> whether the program uses floating point are insufficient, and
> the programmer must sometimes insert an extra, explicit call to
> a floating-point library routine (such as sqrt(); any will do)
> to force loading of floating-point support. (See the
comp.os.msdos.programmer FAQ list for more information.)
==========
< Under a pre-ANSI compiler, rewrite the function definition
< without a prototype ("char *vstrcat(first) char *first; {"),
< include <stdio.h> rather than <stdlib.h>, add "extern
< char *malloc();", and use int instead of size_t. You may also
< have to delete the (void) casts, and use the older varargs
< package instead of stdarg. See also question 15.7.
---
> See also question 15.7.
==========
A: There's an older header, <varargs.h>, which offers about the
same functionality.
< To rewrite the error() function from question 15.5 to use
< <varargs.h>, change the function header to:
<
< void error(va_alist)
< va_dcl
< {
< char *fmt;
<
< change the va_start line to
<
< va_start(argp);
<
< and add the line
<
< fmt = va_arg(argp, char *);
<
< between the calls to va_start and vfprintf. (Note that there is
< no semicolon after va_dcl.)
==========
use va_arg(argp, double). Similarly, use va_arg(argp, int) to
retrieve arguments which were originally char, short, or int.
> (For analogous reasons, the last "fixed" argument, as handed to
> va_start(), should not be widenable.)
==========
omitted declaration of external functions, especially
< those which return something other than int
---
omitted declaration of external functions, especially
> those which return something other than int, or have
> "narrow" or variable arguments
==========
improper malloc/free use: assuming malloc'ed memory
contains 0, assuming freed storage persists, freeing
< something twice (see also questions 7.20 and 7.19)
---
> something twice, corrupting the malloc arena (see also
> questions 7.19 and 7.20)
==========
< trying to malloc(256 * 256 * sizeof(double)), especially
---
> trying to allocate more memory than an unsigned int can
> count, especially on machines with limited memory (see
also questions 7.16 and 19.23)
==========
A: These generally mean that your program tried to access memory it
< shouldn't have, invariably as a result of improper pointer use.
< Likely causes are inadvertent use of null pointers (see also
---
> shouldn't have, invariably as a result of stack corruption or
> improper pointer use. Likely causes are overflow of local
> ("automatic," stack-allocated) arrays; inadvertent use of null
==========
tools to compute code ccount, Metre, lcount, or
metrics csize, or see URL
< http://www.qucis.queensu.ca:1999/Software-
Engineering/Cmetrics.html ;
---
> http://www.qucis.queensu.ca/Software-
Engineering/Cmetrics.html ;
==========
a C lines-of-source this can be done very
counter crudely with the standard
Unix utility wc, and
< considerably better with
---
> somewhat better with
grep -c ";"
==========
> a C declaration aid see question 1.21
> (cdecl)
==========
< Sentinel, from AIB Software, 1145 Herndon Pkwy #200, Herndon,
< VA 22070, USA, 703-787-7700, 800-296-3000, info@aib.com .
---
> Final Exam Memory Advisor, from PLATINUM Technology
> (formerly Sentinel from AIB Software), 1815 South Meyers
> Rd., Oakbrook Terrace, IL 60181, USA, 630-620-5000,
> 800-442-6861, info@platinum.com, www.platinum.com .
==========
> ZeroFault, from The Kernel Group, 1250 Capital of Texas
> Highway South, Building Three, Suite 601, Austin,
> TX 78746, 512-433-3333, http://www.tkg.com, zf@tkg.com .
==========
archive sites. An MS-DOS port, djgpp, is also available; it can
< be found in the Simtel and Oakland archives and probably many
< others, usually in a directory like pub/msdos/djgpp/ or
< simtel/msdos/djgpp/.
---
> be found at ftp.delorie.com in pub/djgpp, or at the various
> SimTel mirrors (e.g. ftp.simtel.net in pub/simtelnet/gnu/djgpp;
> ftp.coast.net in SimTel/vendors/djgpp).
==========
> A shareware MS-DOS C compiler is available from
> ftp.hitech.com.au/hitech/pacific. Registration is optional for
> non-commercial use.
==========
In the absence of lint, many modern compilers do attempt to
< diagnose almost as many problems as lint does.
---
> diagnose almost as many problems as lint does. (Many netters
> recommend gcc -Wall -pedantic .)
==========
18.8: Don't ANSI function prototypes render lint obsolete?
< A: Not really. First of all, prototypes work only if they are
---
> A: No. First of all, prototypes work only if they are present and
==========
The Coronado Enterprises C tutorials are available on Simtel
< mirrors in pub/msdos/c/.
---
> mirrors in pub/msdos/c or on the web at http://www.swcp.com/~dodrill .
==========
> Martin Brown has C course material on the web at http://www-
> isis.ecs.soton.ac.uk/computing/c/Welcome.html .
==========
> Finally, the author of this FAQ list teaches a C class and has
> begun putting its notes on the web; they are at
> http://www.eskimo.com/~scs/cclass/cclass.html .
==========
< [Disclaimer: I have not reviewed these tutorials; I have heard
< that at least one of them contains a number of errors. Also,
---
> [Disclaimer: I have not reviewed all of these tutorials, and I
> have heard that at least one of them contains a number of
> errors. With the exception of the one with my name on it, I
> can't vouch for any of them. Also, this sort of information
rapidly becomes out-of-date; these addresses may not work by the
time you read this and try them.]
==========
Vinit Carpenter maintains a list of resources for learning C and
C++; it is posted to comp.lang.c and comp.lang.c++, and archived
where this FAQ list is (see question 20.40), or on the web at
< http://vinny.csd.mu.edu/ .
---
> http://www.cyberdiem.com/vin/learn.html .
==========
K&R's suitability as an initial programming text: many of us did
learn C from it, and learned it well; some, however, feel that
it is a bit too clinical as a first tutorial for those without
< much programming background.
---
> much programming background. Several sets of annotations and
> errata are available on the net, see e.g.
> http://www.csd.uwo.ca/~jamie/.Refs/.Footnotes/C-annotes.html,
> http://www.eskimo.com/~scs/cclass/cclass.html, and
> http://www.lysator.liu.se/c/c-errata.html#main .
==========
> The Association of C and C++ Users (ACCU) maintains a
> comprehensive set of bibliographic reviews of C/C++ titles, at
> http://bach.cis.temple.edu/accu/bookcase or
> http://www.accu.org/accu .
==========
If you have access to Usenet, see the regular postings in the
comp.sources.unix and comp.sources.misc newsgroups, which
describe the archiving policies for those groups and how to
< access their archives. The comp.archives newsgroup contains
---
> access their archives, two of which are
> ftp://gatekeeper.dec.com/pub/usenet/comp.sources.unix/ and
> ftp://ftp.uu.net/usenet/comp.sources.unix/. The comp.archives
==========
assuming it provides one. Since comp.lang.c is oriented towards
< topics that C does deal with, you will usually get better
---
> those topics that the C language has defined support for, you
will usually get better answers to other questions by referring
to a system-specific newsgroup such as comp.unix.questions or
comp.os.msdos.programmer, and to the FAQ lists for these groups.
==========
For clearing the screen, a halfway portable solution is to print
a form-feed character ('\f'), which will cause some displays to
< clear. Even more portable would be to print enough newlines to
---
> clear. Even more portable might be to print enough newlines to
scroll everything away.
==========
Three possible test routines are stat(), access(), and fopen().
< (To make an approximate test for file existence with fopen(),
< just open for reading and close immediately.) Of these, only
---
> (To make an approximate test using fopen(), just open for
> reading and close immediately, although failure does not
> necessarily indicate nonexistence.) Of these, only fopen() is
widely portable, and access(), where it exists, must be used
carefully if the program uses the Unix set-UID feature.
==========
Under Unix, the stat() call will give you an exact answer.
Several other systems supply a Unix-like stat() which will give
an approximate answer. You can fseek() to the end and then use
< ftell(), but these tend to have the same problems: fstat() is
---
> ftell(), or maybe try fstat(), but these tend to have problems:
fstat() is not portable, and generally tells you the same thing
stat() tells you; ftell() is not guaranteed to return a byte
count except for binary files.
==========
< A: There are actually at least two resource limitations on the
---
> A: There are typically at least two resource limitations on the
number of simultaneously open files: the number of low-level
"file descriptors" or "file handles" available in the operating
system, and the number of FILE structures available in the stdio
==========
to allocate huge amounts of it contiguously. (The C Standard
< does not guarantee that a single object can be larger than 32K.)
---
> does not guarantee that single objects can be 32K or larger.)
==========
If you're using a PC-compatible (8086-based) system, and running
< up against a 640K limit, consider using "huge" memory model, or
---
> up against a 64K or 640K limit, consider using "huge" memory
model, or expanded or extended memory, or malloc variants such
as halloc() or farmalloc(), or a 32-bit "flat" compiler (e.g.
djgpp, see question 18.3), or some kind of a DOS extender, or
another operating system.
==========
A: Use the library function system(), which does exactly that.
< Note that system's return value is the command's exit status,
---
> Note that system's return value is at best the command's exit
> status (although even that is not guaranteed), and usually has
nothing to do with the output of the command.
==========
System V and POSIX. Other routines you might look for on your
system include clock(), delay(), gettimeofday(), msleep(),
< nap(), napms(), setitimer(), sleep(), times(), and usleep().
---
> nap(), napms(), nanosleep(), setitimer(), sleep(), times(), and
usleep().
==========
A: You're out of luck. Either you misunderstood your requirement,
or it's an impossible one to meet. ANSI/ISO Standard C simply
< does not define ways of doing these things. (POSIX defines a
< few.)
---
> does not define ways of doing these things; it is a language
> standard, not an operating system standard. An international
> standard which does address many of these issues is POSIX
> (IEEE 1003.1, ISO/IEC 9945-1), and many operating systems (not
> just Unix) now have POSIX-compatible programming interfaces.
==========
< 20.13: How can I make my code more efficient?
<
< A: Efficiency, though a favorite comp.lang.c topic, is not
< important nearly as often as people tend to think it is. Most
---
> 20.13: What's the best way of making my program efficient?
>
> A: By picking good algorithms, implementing them carefully, and
> making sure that your program isn't doing any extra work. For
> example, the most microoptimized character-copying loop in the
> world will be beat by code which avoids having to copy
> characters at all.
>
> When worrying about efficiency, it's important to keep several
> things in perspective. First of all, although efficiency is an
> enormously popular topic, it is not always as important as
> people tend to think it is. Most of the code in most programs
is not time-critical. When code is not time-critical, it is
usually more important that it be written clearly and portably
than that it be written maximally efficiently.
==========
< efficiently. (Remember that computers are very, very fast, and
< that even "inefficient" code can run without apparent delay.)
---
> than that it be written maximally efficiently. (Remember that
> computers are very, very fast, and that seemingly "inefficient"
> code may be quite efficiently compilable, and run without
> apparent delay.)
==========
< Even for code that *is* time-critical, it is not as important to
< "microoptimize" the coding details. Many of the "efficient
---
> Even for code that *is* time-critical, one of the least
> effective optimization techniques is to fuss with the coding
> details. Many of the "efficient coding tricks" which are
==========
(As it happens, parentheses are optional with the sizeof
< operator, too, as long as its operand is a variable or a unary
< expression.)
---
> operator, too, under certain circumstances.)
==========
many potential uses of nested functions (e.g. qsort comparison
functions), an adequate if slightly cumbersome solution is to
use an adjacent function with static declaration, communicating
< if necessary via a few static variables. (A cleaner solution
< when such functions must communicate is to pass around a pointer
---
> if necessary via a few static variables. (A cleaner solution,
> though unsupported by qsort(), is to pass around a pointer to
a structure containing the necessary context.)
==========
Conversely, ANSI C inherited several features from C++,
including prototypes and const, so neither language is really a
< subset or superset of the other. In spite of the differences,
---
> subset or superset of the other; the two also define the meaning
> of some common constructs differently. In spite of the
==========
A: Use mktime() or localtime() (see questions 13.13 and 13.14, but
beware of DST adjustments if tm_hour is 0), or Zeller's
congruence (see the sci.math FAQ list), or this elegant code by
Tomohiko Sakamoto:
dayofweek(y, m, d) /* 0 = Sunday */
int y, m, d; /* 1 <= m <= 12, y > 1752 or so */
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
> (Copyright 1993, Tomohiko Sakamoto)
==========
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
main(){printf(s,34,s,34);}
< (This program, like many of the genre, assumes that the double-
---
> (This program, like many of the genre, neglects to #include
> <stdio.h>, and assumes that the double-quote character " has the
value 34, as it does in ASCII.)
==========
< Contest winners should be announced at the winter USENIX
conference in January, and are posted to the net sometime
thereafter. Winning entries from previous years (back to 1984)
are archived at ftp.uu.net (see question 18.16) under the
< directory pub/ioccc/.
---
> Contest winners should be announced at the USENIX conference in
January, and are posted to the net sometime thereafter. Winning
entries from previous years (back to 1984) are archived at
ftp.uu.net (see question 18.16) under the directory pub/ioccc/;
> see also http://reality.sgi.com/csp/ioccc/ .
==========
A: You can pronounce the C keyword "char" in at least three ways:
< like the English words "char," "care," or "car;" the choice is
---
> like the English words "char," "care," or "car" (or maybe even
> "character"); the choice is arbitrary.
==========
< An extended version of this FAQ list is being published by
---
> An extended version of this FAQ list has been published by
Addison-Wesley as _C Programming FAQs: Frequently Asked
Questions_ (ISBN 0-201-84519-9).
==========
< It should be available in November 1995.
==========
> An errata list is at
> http://www.eskimo.com/~scs/C-faq/book/Errata.html and on
> ftp.eskimo.com in u/s/scs/ftp/C-faq/book/Errata .
==========
< This list is an evolving document of questions which have been
< Frequent since before the Great Renaming, not just a collection
< of this month's interesting questions. Older copies are
---
> This list is an evolving document containing questions which
> have been Frequent since before the Great Renaming; it is not
> just a collection of this month's interesting questions. Older
copies are obsolete and don't contain much, except the
occasional typo, that the current list doesn't.
==========
Thanks to Jamshid Afshar, David Anderson, Tanner Andrews, Sudheer Apte,
Joseph Arceneaux, Randall Atkinson, Rick Beem, Peter Bennett, Wayne
Berke, Dan Bernstein, Tanmoy Bhattacharya, John Bickers, Gary Blaine,
> Yuan Bo, Mark J. Bobak, Dave Boutcher, Alan Bowler, Michael Bresnahan,
> Walter Briscoe, Vincent Broman, Stan Brown, John R. Buchan, Joe Buehler,
> Kimberley Burchett, Gordon Burditt, Scott Burkett, Burkhard Burow, Conor
P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill, Vinit
> Carpenter, Paul Carter, Mike Chambers, Billy Chambless, C. Ron Charlton,
Franklin Chen, Jonathan Chen, Raymond Chen, Richard Cheung, Steve
Clamage, Ken Corbin, Ian Cottam, Russ Cox, Jonathan Coxhead, Lee
> Crawford, Nick Cropper, Steve Dahmer, Andrew Daviel, James Davies, John
> E. Davis, Ken Delong, Norm Diamond, Bob Dinse, Jeff Dunlop, Ray Dunn,
> Stephen M. Dunn, Michael J. Eager, Scott Ehrlich, Arno Eigenwillig, Yoav
> Eilat, Dave Eisen, Joe English, Bjorn Engsig, David Evans, Clive D.W.
Feather, Dominic Feeley, Simao Ferraz, Chris Flatters, Rod Flores,
> Alexander Forst, Steve Fosdick, Jeff Francis, Ken Fuchs, Tom Gambill,
Dave Gillespie, Samuel Goldstein, Tim Goodwin, Alasdair Grant, Ron
> Guilmette, Doug Gwyn, Michael Hafner, Darrel Hankerson, Tony Hansen,
Elliotte Rusty Harold, Joe Harrington, Des Herriott, Guy Harris, John
> Hascall, Ger Hobbelt, Jos Horsmeier, Syed Zaeem Hosain, Blair Houghton,
James C. Hu, Chin Huang, David Hurt, Einar Indridason, Vladimir
Ivanovic, Jon Jagger, Ke Jin, Kirk Johnson, Larry Jones, Arjan Kenter,
> Bhaktha Keshavachar, James Kew, Darrell Kindred, Lawrence Kirby, Kin-
ichi Kitano, Peter Klausler, Andrew Koenig, Tom Koenig, Adam Kolawa,
> Jukka Korpela, Ajoy Krishnan T, Jon Krom, Markus Kuhn, Deepak Kulkarni,
Oliver Laumann, John Lauro, Felix Lee, Mike Lee, Timothy J. Lee, Tony
Lee, Marty Leisner, Don Libes, Brian Liedtke, Philip Lijnzaad, Keith
Lindsay, Yen-Wei Liu, Paul Long, Christopher Lott, Tim Love, Tim
> McDaniel, J. Scott McKellar, Kevin McMahon, Stuart MacMartin, John R.
MacMillan, Andrew Main, Bob Makowski, Evan Manning, Barry Margolin,
> George Matas, Brad Mears, Wayne Mery, De Mickey, Rich Miller, Roger
Miller, Bill Mitchell, Mark Moraes, Darren Morby, Bernhard Muenzer,
David Murphy, Walter Murray, Ralf Muschall, Ken Nakata, Todd Nathan,
> Taed Nelson, Landon Curt Noll, Tim Norman, Paul Nulsen, David O'Brien,
> Richard A. O'Keefe, Adam Kolawa, Keith Edward O'hara, James Ojaste, Hans
Olsson, Bob Peck, Andrew Phillips, Christopher Phillips, Francois
> Pinard, Nick Pitfield, Wayne Pollock, Polver@aol.com, Dan Pop, Claudio
> Potenza, Lutz Prechelt, Lynn Pye, Kevin D. Quitt, Pat Rankin, Arjun Ray,
> Eric S. Raymond, Peter W. Richards, James Robinson, Eric Roode, Manfred
Rosenboom, J. M. Rosenstock, Rick Rowe, Erkki Ruohtula, John Rushford,
Kadda Sahnine, Tomohiko Sakamoto, Matthew Saltzman, Rich Salz, Chip
Salzenberg, Matthew Sams, Paul Sand, DaviD W. Sanderson, Frank Sandy,
Christopher Sawtell, Jonas Schlein, Paul Schlyter, Doug Schmidt, Rene
> Schmit, Russell Schulz, Dean Schulze, Chris Sears, Peter Seebach,
> Patricia Shanahan, Aaron Sherman, Raymond Shwake, Peter da Silva, Joshua
Simons, Ross Smith, Henri Socha, Leslie J. Somos, Henry Spencer, David
> Spuler, Frederic Stark, James Stern, Zalman Stern, Michael Sternberg,
> Alan Stokes, Bob Stout, Steve Sullivan, Melanie Summit, Erik Talvola,
Dave Taylor, Clarke Thatcher, Wayne Throop, Chris Torek, Steve Traugott,
Ilya Tsindlekht, Andrew Tucker, Goran Uddeborg, Rodrigo Vanegas, Jim Van
Zandt, Wietse Venema, Tom Verhoeff, Ed Vielmetti, Larry Virden, Chris
Volpe, Mark Warren, Alan Watson, Kurt Watzka, Larry Weiss, Martin
> Weitzel, Howard West, Tom White, Freek Wiedijk, Tim Wilson, Dik T.
Winter, Lars Wirzenius, Dave Wolverton, Mitch Wright, Conway Yee, Ozan
S. Yigit, and Zhuo Zang, who have contributed, directly or indirectly,
to this article.
==========
> Thanks to the reviewers of the book-length version:
> Mark Brader, Vinit Carpenter, Stephen Clamage, Jutta Degener, Doug Gwyn,
> Karl Heuer, and Joseph Kent. Thanks to Debbie Lafferty and Tom Stone at
> Addison-Wesley for encouragment, and permission to cross-pollinate this
> list with new text from the book.
==========
> Except as noted otherwise, the C code in this article is public domain
> and may be used without restriction.
==========
Steve Summit
scs@eskimo.com